--[[
连接上zk后，发送 ConnectRequest,并获取了响应

解析响应，并存储状态
发送 getchildren请求，并获得响应，解析响应

--]]

local myutils = require('myutils')
local request = require('request')
local response = require('response')
local sock = require('socket')
local host = 'localhost'
local port = 2181

--local _M = {}
--setfenv(1, _M)

local _status = {
    xid = 0,
    lastZxidSeen = 0, -- Uint8Array[8]
    timeOut = 30000,
    sessionId = 0, -- Uint8Array[8]
    passwd = myutils.makeBuffer(16) -- Uint8Array[16]
}

local req1 = request:new("ConnectRequest", nil, {
    protocolVersion = 0,
    lastZxidSeen = _status.lastZxidSeen,
    timeOut = _status.timeOut,
    sessionId = _status.sessionId,
    passwd = _status.passwd
})
--print(type(req1))
--myutils.printTbl(req1.payload)
--myutils.writeFile(req1:toStream())


local conn = assert(sock.connect(host, port))
conn:send(req1:toStream())

local b1 = conn:receive(4)
--myutils.writeFile(b1)
local length = response.unpackInt(b1)
print('length=' .. length)
local b2 = conn:receive(length)
--myutils.writeFile(b2)
local resp1 = response:new('ConnectResponse', b2)
resp1:parse()
--myutils.printTbl(req1.header)
--myutils.printTbl(req1.payload)
_status.timeout = resp1.payload.timeout
_status.sessionId = resp1.payload.sessionId
_status.passwd = resp1.payload.passwd


-- send get children request
print("phase GetChildren2Request")
_status.xid = _status.xid + 1
local header = { xid = _status.xid, type = request.OP_CODES.GET_CHILDREN2 }
local payload = { path = '/bar', watch = 0 }
local req2 = request:new("GetChildren2Request", header, payload)
--req2:toStream()
--myutils.writeFile(req2:toStream())

conn:send(req2:toStream())
local b3 = conn:receive(4) -- first 4 byte = package length
local length = response.unpackInt(b3)
print('length=' .. length)
local b4 = conn:receive(length)
myutils.writeFile(b4)
local resp2 = response:new('getChildren2Response', b4)
resp2:parse()
resp2:showInfo()
print(resp2.payload.children[1])
print(resp2.payload.children[2])



conn:close()